package top.lidee.framework.result;


import com.thoughtworks.xstream.core.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanCreationException;
import top.lidee.framework.enums.CommonExceptionEnum;
import top.lidee.repository.model.twice.local.LoginUserLoc;

import java.util.Objects;
import java.util.Optional;


import static top.lidee.framework.enums.CommonExceptionEnum.NOT_PERMISSION;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/9/3 22:23
 */
@Slf4j
public class GlobalCheck {

    /**
     * 判断当前用户是否是商户
     * @param merchantId
     * @return
     */
    public static Integer checkMerchantId(Integer merchantId) {
        //判断当前用户是否是商户
        if (Objects.isNull(merchantId) || Objects.equals(merchantId, 0)) {
            throw new BeanCreationException(NOT_PERMISSION.getMsg());
        }
        return merchantId;
    }

    /**
     * 校验当前登录者是否为代理商或内部管理员
     * @param managerId
     * @return
     */
    public static Integer checkManagerAdmin(Integer managerId) {
        return checkMerchantId(managerId);
    }


    /**
     * 校验当前登录者是否为admin
     * @param managerId
     * @return
     */
    public static Integer checkAdmin(Integer managerId) {
        //判断当前用户是否是商户
        if (Objects.isNull(managerId) || !Objects.equals(managerId, 1)) {
            throw new BeanCreationException(NOT_PERMISSION.getMsg());
        }
        return managerId;
    }


    /**
     * 小程序端校验本地线程用户信息
     *
     * @param loginUserLoc
     * @return
     */
    public static LoginUserLoc checkUserLoc(ThreadLocal<LoginUserLoc> loginUserLoc) {
        LoginUserLoc loc = Optional.ofNullable(loginUserLoc.get()).orElse(new LoginUserLoc());
        if (Objects.isNull(loc.getUserId())) {
            log.error(CommonExceptionEnum.NOAUTH.getMsg());
            throw new BeanCreationException(CommonExceptionEnum.NOAUTH.getMsg());
        }
        return loc;
    }
}
